package cn.xyy.system.service;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import cn.xyy.common.file.FileConstants;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import cn.xyy.common.file.FileUtils;
import cn.xyy.common.utils.DateUtils;
import cn.xyy.common.utils.LoggerUtil;
import cn.xyy.common.utils.StringUtils;
import cn.xyy.common.config.ConfigUtil;
import cn.xyy.common.exception.SystemException;

/**
 * 文件服务业务
 * 
 * @author xyy
 *
 */
@Service
public class FileService {

	public Map<String, String> uploadTinymce(MultipartFile multipartFile) {
		Map<String, String> map = new HashMap<String, String>();
		// 文件大小验证
		try {
			FileUtils.checkSize(FileConstants.tinymceMaxSize, multipartFile.getSize());

			// 验证文件上传的格式
			String image = "gif jpg png jpeg";
			String fileType = FileUtils.getExtensionName(multipartFile.getOriginalFilename());
			if (fileType != null && !image.contains(fileType)) {
				throw new SystemException("文件格式错误！, 仅支持 " + image + " 格式");
			}

			String name = FileUtils.getFileNameNoEx(multipartFile.getOriginalFilename());
			String suffix = FileUtils.getExtensionName(multipartFile.getOriginalFilename());
			String fileName = name + "_" + DateUtils.getDateTimeNoBar() + "." + suffix;
			String path = ConfigUtil.getAppConfig().getFile().getPath() + FileConstants.tinymce + "/" + fileName;

			File file = FileUtils.upload(multipartFile.getBytes(), path);
			map.put("fileName", file.getName());
		} catch (Exception e) {
			LoggerUtil.error(e.getMessage());
			throw new SystemException("图片上传失败");
		}

		return map;
	}

	public void downLoadTinymce(String fileName) {
		if (StringUtils.isBlank(fileName)) {
			return;
		}
		try {
			String path = ConfigUtil.getAppConfig().getFile().getPath() + FileConstants.tinymce + "/" + fileName;
			FileUtils.download(path);
		} catch (Exception e) {
			LoggerUtil.error(e.getMessage());
		}
	}

}
